//index.js
import * as echarts from '../../ec-canvas/echarts';
//获取应用实例
const app = getApp()
var indexJson = require('../../data/indexJson');
var navListJson = require('../../data/navListJson');
var util =  require('../../utils/util.js');
let PieChart = null;
let BarChart = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    btnTxt: {
      btnTxt: '记录体重'
    },
    ec: {
      // lazyLoad: true // 延迟加载
    },
    ec2: {
      // lazyLoad: true // 延迟加载
    },
    puid: '',
    currentTab: 0,//当前页面
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (res) {
    var that = this
    if(res.puid)
    {
      app.globalData.puid = res.puid
    }
    that.setData({
      date: util.setTime7(new Date()),
      navList: navListJson.indexNavList,
      moduleTitleList: indexJson.moduleTitleList,
    })
    that.getUserOpenid();
    that.piechartsComponnet = that.selectComponent('#mychartPie');
    that.barchartsComponnet = that.selectComponent('#mychartBar');
    that.getPieGraphData();
    that.getBarGraphData();
  },
  
  //获取用户openid
  getUserOpenid:function(){
    var that = this;
    wx.login({
      success:function(res){
        console.log(res.code)
        // 发送请求
        wx.request({
            url: app.globalData.apiUrl +'/get_openid', //接口地址
            data: {
                code:res.code,
            },
            method: 'get',
          header: {
              'content-type': 'application/json' //默认值
          },
          success: function (res) {
            console.log(res)
            //判断用户是否存在
            if(res.data.code == 1){
              //后台有数据
              app.globalData.userId = res.data.data.id;
              // console.log(app.globalData.userId);
              if(!app.globalData.isAuthorized){
                wx.navigateTo({
                  url: '../authorizedLogin/authorizedLogin?isLogin='+ 'true',
                })
              }
              that.getIndexData();
              // console.log(app.globalData.isAuthorized)
              that.setData({
                userInfo: app.globalData.userInfo
              })
            }else {
              app.globalData.openid = res.data.openid
              if(app.globalData.isAuthorized){
                //用户没有登录过 但是已经授权
                wx.redirectTo({
                  url: '../login/login'
                })
              }else{
                wx.navigateTo({
                  url: '../authorizedLogin/authorizedLogin?isLogin='+ 'false',
                })
              }
            }
          }
        })
      }
    })
  },

  //获得数据
  getIndexData:function(){
    var that = this
    // console.log(app.globalData.userId)
    wx.request({
      url: app.globalData.apiUrl +'/first_content', //接口地址
      data: {
        userid: app.globalData.userId,
      },
      method: 'get',
      header: {
          'content-type': 'application/json' //默认值
      },
      success: function (res) {
        console.log(res)
        if(res.data.code == '200'){
          that.getWeightData(res.data.data.weight);
          that.getFootData(res.data.data.foot);
          that.getSportData(res.data.data.sport);
          that.getBloodData(res.data.data.blood);
          that.getSugarData(res.data.data.sugar);
          that.getFatData(res.data.data.sugarfat);
        }else{
          util.showModal('提示','数据异常')
          return;
        }
      }
    })
  },

  //计算体重
  getWeightData:function(weight){
    var that = this
    if(weight){
      let percent = (weight.startweight - weight.currentweight) / (weight.startweight - weight.targetweight)
      // console.log(percent)
      that.setData({
        currentWeight: weight.weight,//当前体重
        startWeight: weight.startweight,//初始体重
        targetWeight: weight.targetweight,//目标体重
        bmi: weight.bmi,
        bmiTip: that.setBmi(weight.bmi)[0],
        bmiColor: that.setBmi(weight.bmi)[1],
        percent: percent
      })
      if(that.data.percent && that.data.percent!= 0){
        that.anim(that.data.percent);
      }
    }else{
      that.setData({
        currentWeight: 0,//当前体重
        startWeight: 0,//初始体重
        targetWeight: 0,//目标体重
        bmi: 0,
        percent: 0
      })
    }
  },

  //设置BMI
  setBmi:function(bmi){
    var arr = []
    var bmiTip = ''
    var bmiColor = ''
    if(bmi < 18.5){
      bmiTip = '偏低'
      bmiColor = '#49bdf9'
    }
    if(bmi >= 18.5 && bmi < 24){
      bmiTip = '正常'
      bmiColor = '#1fab57'
    }
    if(bmi >= 24 && bmi < 28){
      bmiTip = '轻度肥胖'
      bmiColor = '#f5bc51'
    }
    if(bmi > 28 && bmi <= 32){
      bmiTip = '肥胖'
      bmiColor = '#fa8b20'
    }
    if(bmi > 32){
      bmiTip = '重度肥胖'
      bmiColor = '#d65e5d'
    }
    arr.push(bmiTip,bmiColor)
    return arr
  },

  //获得饮食记录
  getFootData:function(foot){
    var that = this
    if(foot.length != 0){
      for(let i in foot)
      {
        if(foot[i].createtime){
          that.setData({
            footTime: util.setTime9(foot[i].createtime)
          })
        }
        switch (foot[i].remark) {
          case '早餐':
            that.setData({
              breakfastPicList: foot[i].list
            })
            break;
          case '午餐':
            that.setData({
              lunchPicList: foot[i].list
            })
            break;
          case '晚餐':
            that.setData({
              dinnerPicList: foot[i].list
            })
            break;
        }
      }
    }else{
      that.setData({
        breakfastPicList: [],
        lunchPicList: [],
        dinnerPicList: [],
        footTime: that.data.date
      })
    }
  },

  //获得运动记录
  getSportData:function(sport){
    var that = this;
    if(sport)
    {
      var exerciseList = indexJson.exerciseList;
      for(let i in exerciseList){
        switch (exerciseList[i].index) {
          case 1:
            exerciseList[i].data = sport.num
            break;
          case 2:
            exerciseList[i].data = sport.kpa
            break;
          case 3:
            exerciseList[i].data = util.ChangeHourMinutestr(sport.time)
            break;
        }
      }
      that.setData({
        exerciseList: exerciseList
      })
    }else{
      that.setData({
        exerciseList: indexJson.exerciseList2
      })
    }
  },

  //获得血压数据
  getBloodData:function(blood){
    var that = this
    if(blood){
      that.setData({
        bloodHeight: blood.height,
        bloodLow: blood.low,
        bloodHeart: blood.heart,
        bloodTime: util.setTime8(blood.createtime)
      })
    }else{
      that.setData({
        bloodHeight: '-',
        bloodLow: '-',
        bloodHeart: '-',
        bloodTime: that.data.date
      })
    }
    
  },

  //获得血糖数据
  getSugarData:function(sugar){
    var that = this 
    if(sugar.count > 0){
      that.setData({
        isCount: true
      })
    }
    if(sugar.list.length != 0){
      var sugarList = indexJson.sugarList
      for(let i in sugar.list){
        let item = sugar.list[i]
        switch (item.type) {
          case 1:
            sugarList[0].data = item.blood
            break;
          case 2:
            sugarList[1].data = item.blood
            break;
          case 3:
            sugarList[2].data = item.blood
            break;
          case 4:
            sugarList[3].data = item.blood
            break;
          case 5:
            sugarList[4].data = item.blood
            break;
          case 6:
            sugarList[5].data = item.blood
            break;
        }
      }
      that.setData({
        sugarList: sugarList
      })
    }else{
      that.setData({
        sugarList: indexJson.sugarList,
      })
    }
  },

  //获得血脂数据
  getFatData:function(fat){
    var that = this
    if(fat){
      var fatList = indexJson.fatList
      for(let i in fatList)
      {
        switch (fatList[i].index) {
          case 1:
            fatList[i].data = fat.cholesterol
            break;
          case 2:
            fatList[i].data = fat.glycerol
            break;
          case 3:
            fatList[i].data = fat.uric
            break;
          case 4:
            fatList[i].data = fat.hdl
            break;
          case 5:
            fatList[i].data = fat.ldl
            break;
        }
      }
      that.setData({
        fatList: fatList
      })
    }else{
      that.setData({
        fatList: indexJson.fatList2
      })
    }
  },

  //动画 计算进度条
  anim:function(percent){
    var that = this
    var animation = wx.createAnimation({
      duration: 200,  //动画时长
      timingFunction: 'linear', //线性
      delay: 0  //0则不延迟
    });
    // 第2步：这个动画实例赋给当前的动画实例
    that.animation = animation;
    animation.translateX(250 * (percent / 100)).step()
    // console.log(animation)
    that.setData({
      ifPercent: true,
      animationData: animation.export()
    })
  },

  //设置单位
  setUtil:function(dataList){
    var that = this
    for(var i in dataList){
      if(dataList[i].title == '体重')
      {
        var util = "dataList[" + i + "].util"
        that.setData({
          [util]: '（kg）',
        })
      }
      if(dataList[i].title == 'BMI')
      {
        var util = "dataList[" + i + "].util"
        that.setData({
          [util]: '',
        })
      }
      if(dataList[i].title == '体脂率')
      {
        var util = "dataList[" + i + "].util"
        that.setData({
          [util]: '（%）',
        })
      }
      if(dataList[i].title == '肌肉量')
      {
        var util = "dataList[" + i + "].util"
        that.setData({
          [util]: '（kg）',
        })
      }
      if(dataList[i].title == '体年龄')
      {
        var util = "dataList[" + i + "].util"
        that.setData({
          [util]: '（岁）',
        })
      }
      if(dataList[i].title == '水分率')
      {
        var util = "dataList[" + i + "].util"
        that.setData({
          [util]: '（%）',
        })
      }
      if(dataList[i].title == '内脏脂肪')
      {
        var util = "dataList[" + i + "].util"
        that.setData({
          [util]: '',
        })
      }
      if(dataList[i].title == '骨量')
      {
        var util = "dataList[" + i + "].util"
        that.setData({
          [util]: '（kg）',
        })
      }
      if(dataList[i].title == '基础代谢')
      {
        var util = "dataList[" + i + "].util"
        that.setData({
          [util]: '（kcal）',
        })
      }
      if(dataList[i].title == '蛋白质率')
      {
        var util = "dataList[" + i + "].util"
        that.setData({
          [util]: '（%）',
        })
      }
    }
  },

  //饼状图表
  getPieGraphData:function(){
    // if(data == null || time == null) return;
    var that = this
    if (!PieChart){
      that.init_pieEcharts(); //初始化图表
    }else{
      that.setPieOption(); //更新数据
    }
  },

  //初始化图表
  init_pieEcharts: function () {
    var that = this
    that.piechartsComponnet.init((canvas, width, height) => {
      // 初始化图表
      PieChart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      PieChart.showLoading({
        text : '正在努力的读取数据中...'
      });
      // PieChart.setPieOption(this.getBarOption());
      that.setPieOption();
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return PieChart;
    });
  },

  setPieOption: function () {
    PieChart.clear();  // 清除
    PieChart.setOption(this.getPieOption());  //获取新数据
  },

  //设置饼状图表
  getPieOption: function () {
    // 指定图表的配置项和数据
    var option = {
      // tooltip: {
      //   trigger: 'item',
      //   formatter: "{b}: {c} "
      // },
      series : [{
        name:'',
        type:'pie',
        radius: ['60%', '90%'],
        center: ['50%', '50%'],
        hoverAnimation: true,
        silent: true, //图形是否不响应和触发鼠标事件
        label: {
          normal: {
            position: 'center',
            show: true,
            height: 60
          }
        },
        itemStyle:{
          color: '#dddbdb',
          borderColor:'#fff',
          borderWidth: 2,
          borderType: 'solid'
        },
        data:[
          {
            value:90,
            name:'生理年龄',
            itemStyle:{
              color: '#45a08f',
            },
            label:{
              normal:{
                formatter: [
                  '{num|{c}}',
                  '{score|SCORE}',
                  '{name|{b}}',
                ].join('\n'),
                rich: {
                  num: {
                    color: '#1d1d1d',
                    fontSize: 38,
                  },
                  score: {
                    color: '#d5d5d5',
                    fontSize: 12,
                    padding: [10,0]
                  },
                  name:{
                    color: '#707070',
                    fontSize: 18,
                  }
                }
              }
            }
          },{
            value:10,
            itemStyle:{
              color: '#dddbdb',
            }
          }
        ]
      }]
    };
    PieChart.hideLoading()
    return option;
  },

  //柱状图表
  getBarGraphData:function(){
    // if(data == null || time == null) return;
    var that = this
    if (!BarChart){
      that.init_barEcharts(); //初始化图表
    }else{
      that.setBarOption(); //更新数据
    }
  },

  //初始化图表
  init_barEcharts: function () {
    var that = this
    that.barchartsComponnet.init((canvas, width, height) => {
      // 初始化图表
      BarChart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      BarChart.showLoading({
        text : '正在努力的读取数据中...'
      });
      // BarChart.setBarOption(this.getBarOption());
      that.setBarOption();
      // BarChart.dispatchAction({
      //   type: 'highlight',
      //   seriesIndex: 0,
      //   dataIndex: 0
      // });
      // BarChart.on('click',{seriesIndex: 0},function(e){
      //   that.setData({
      //     recordTime: e.name,
      //     recordData: e.data
      //   })
      // })
      // 注意这里一定要返回 BarChart 实例，否则会影响事件处理等
      return BarChart;
    });
  },

  setBarOption: function () {
    BarChart.clear();  // 清除
    BarChart.setOption(this.getBarOption());  //获取新数据
  },

  //设置柱状图表
  getBarOption: function () {
    // 指定图表的配置项和数据
    var option = {
      // color: ['black','#2f4554', '#61a0a8', '#d48265', '#91c7ae','#749f83',  '#ca8622', 'red'],
      // tooltip: {
      //   trigger: 'axis',
      //   axisPointer: {
      //       type: 'shadow'
      //   }
      // },
      grid:{ 
        borderWidth:0,
        x:10,
        y:10,
        x2:10,
        y2:10,
        containLabel: true
      },
        xAxis: { 
        type: 'value',
        show:true,
        axisLine:{
          show: false,
        },
        axisTick: {
          show: false,
        },
        axisLabel:{
          show: true,
          color: '#3b3a3a'
        },
        splitLine:{
          show: true,
          lineStyle:{
            color: '#9ed0ff'
          }
        },
        max: 50,
      },
      yAxis: {
        type: 'category',
        show:true,
        inverse: true,
        axisLine:{
          show: true,
          lineStyle:{
            color: '#9ed0ff'
          }
        },
        axisTick: {
          show: true,
          lineStyle:{
            color: '#9ed0ff'
          }
        },
        axisLabel:{
          show: true,
          color: '#3b3a3a'
        },
        // axisPointer:{
        //   show:true,
        //   type: 'shadow',
        //   shadowStyle: {
        //     color: 'rgba(214,234,250,0.3)'
        //   }
        // },
        data : ['BMI','体脂率','体蛋白质','基础代谢','体肌肉量','去脂体重','无机盐','骨矿含量'],
      },
      series : [{
        name:'',
        type:'bar',
        barWidth: 15,
        itemStyle : {
          normal: {
            color: function(params) {
              var colorList = [
                'green','#B5C334','#FCCE10','#E87C25','#27727B',
                 '#FE8463','#9BCA63','#FAD860'
              ];
              return colorList[params.dataIndex]
            },
            label : {
              show: true,
              color: '#2a2a2a',
              position: 'right',
              fontSize: 10,
              formatter:function(params){
                // console.log(params)
                let unit  = util.setUnit2(params.name)
                return params.value + unit;
              }
            }
          },
        },
        data:['18','20','20','20','20','20','20','20']
      }]
    };
    BarChart.hideLoading()
    return option;
  },

  //记录体重
  recordWeight:function(){
    var that = this
    wx.navigateTo({
      url: '/subPages/health/recordWeight/recordWeight?weight=' + that.data.currentWeight
    })
  },

  //详情按钮
  details:function(e){
    console.log(e)
    switch (e.currentTarget.dataset.type) {
      case 'pressure':
        wx.navigateTo({
          url: '/subPages/health/pressure/pressure'
        })
        break;
    
      default:
        break;
    }
  },

  //选择导航栏
  switchNav(event){
    var cur = event.currentTarget.dataset.current;      
    if (this.data.currentTab == cur) {
        return false;
    } else {
        this.setData({
            currentTab: cur
        })
    }
  },

  //血糖按钮
  sugar:function(){
    wx.navigateTo({
      url: '/subPages/health/sugar/sugar'
    })
  },

  //血脂按钮
  bloodFat:function(){
    wx.navigateTo({
      url: '/subPages/health/bloodFat/bloodFat'
    })
  },

  //内容滚动
  switchTab(event){
    var cur = event.detail.current;
    this.setData({
        currentTab: cur
    });
  }, 
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.getUserOpenid()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    PieChart = null;
    BarChart = null;
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    PieChart = null;
    BarChart = null;
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: 'PAPN小程序',
      path: 'pages/index/index?puid=' + app.globalData.userId,
      success: function(res) {
          res.shareTickets 
      },
      fail: function(res) {
          console.log(res)
      }
    }
  }
})
